package services

import (
	//"fmt"
	"fmt"
	"strconv"
	"strings"
	"time"

	//"encoding/json"

	"huaxrobot/models"
)


type Plancase struct {
	Testmodel           string `json:"testmodel"`
	Testpriority        string `json:"testpriority"`
}

type PlanJenkinsPlan struct {
	CaseServerity    []string `json:"caseServerity"`
	Project           string `json:"project"`
	Modules           []string `json:"modules"`
	RunningEnv       string `json:"runningEnv"`	
	MailReceiver    string `json:"mailReceiver"`
}

func PlanAdd(planproduct string, planenv string, planmodule string) string {	
	planid := strconv.FormatInt(time.Now().Unix(), 10)	
	plan := models.PlanCase{}
	plan.Create(planid, planproduct, "function", "all", planenv, planmodule, "help4@sany.com.cn", "1111")
	go Runshell(planid)
	//有多个测试model，分为多个任务
/* 	for i, plancase := range plancases {
		subtaskid := planid +  strconv.Itoa(i)
		//message :="planid:" + planid +" " + "subtaskid:" + subtaskid + " " + "testmodel:" + testmodel + " " + "pri:" + testpriority
		message_t := models.TaskInfoMessage{
			PlanId: planid,
			SubTaskID: subtaskid,
			TestEnv: testenv,
			TestModel: plancase.Testmodel,
			TestPrioprity: plancase.Testpriority,
		}
		message_j, _:= json.Marshal(message_t)
		message := string(message_j)
		fmt.Println("send task to kafka:", message)
		//发送kafka消息
		SendTask(message)	
	}	 */
	return planid
}

func PlanJenkinsAdd(plandata PlanJenkinsPlan) string {	
	planid := strconv.FormatInt(time.Now().Unix(), 10)
	caseServerity := strings.Join(plandata.CaseServerity, ",") 
	project := plandata.Project
	runningEnv := plandata.RunningEnv
	modules :=strings.Join(plandata.Modules, ",") 
	mailReceiver := plandata.MailReceiver	
	go planJenkinsAddandWait(planid, caseServerity, project, runningEnv, modules, mailReceiver)
	return planid
}




//将测试plan信息写入数据库，并启动job，等待执行完成后，将数据库执行状态位置真。
func planJenkinsAddandWait(planid string, caseServerity string, project string, runningEnv string, module string, mailReceiver string){	
	plan := models.PlanCase{}	
	queueid := JenkinsAdd(planid, caseServerity, project, runningEnv, module, mailReceiver)
	jenkinsurlo, reportnumber := Jenkinsgetnumber(queueid)
	jenkinsurl := jenkinsurlo + "/allure"
	plan.Create(planid, project,"function", runningEnv,  caseServerity, module, mailReceiver, jenkinsurl)
	//统计job
	record := models.PlanStatistics{}
	date := time.Now().Format("2006-01-02")
	if record.Get(date).Date != date {
		record.Create(date)
		//增加job计数
		record.AddTotalCount(date)
	} else {
		record.AddTotalCount(date)
	}
	//如果当前job已经不是jinkens的当前job，则数据库状态位置真。
	for {		
		lastCompletedBuild := JenkinsJobStatus(reportnumber)
		if lastCompletedBuild == reportnumber {			
			fmt.Println("测试完成，更新测试状态")		
			plan.UpdateStatus(planid)
			//增加通过job计数
			record.AddPassCount(date)
			cost := plan.GetExectTime(planid)
			record.AddExectTime(date, cost)
			break
	} else if lastCompletedBuild > reportnumber {
		fmt.Println("测试完成，更新测试状态")		
		plan.UpdateStatus(planid)
		//增加失败job计数
		record.AddFailCount(date)
		cost := plan.GetExectTime(planid)
		record.AddExectTime(date, cost)
		break
	} else {
		continue
	}
	} 
}

func PlanJenkinsAddbyName(projectname string) string {
	nametmp := strings.Split(projectname, "-")		
	planid := strconv.FormatInt(time.Now().Unix(), 10)
	caseServerity := "all"
	project := "evicloud"
	runningEnv := nametmp[len(nametmp)-1]
	mailReceiver := ""	
	go planJenkinsAddandWaitbyName(planid, caseServerity, project, runningEnv, mailReceiver, projectname)
	return planid
}

func planJenkinsAddandWaitbyName(planid string, caseServerity string, project string, runningEnv string, mailReceiver string, projectname string){	
	plan := models.PlanCase{}	
	queueid := JenkinsAddbyname(projectname)
	jenkinsurl, reportnumber := Jenkinsgetnumber(queueid)
	plan.Create(planid, project,"function", runningEnv, caseServerity,  "all", mailReceiver, jenkinsurl)
	//统计job
	record := models.PlanStatistics{}
	date := time.Now().Format("2006-01-02")
	if record.Get(date).Date != date {
		record.Create(date)
		//增加job计数
		record.AddTotalCount(date)
	} else {
		record.AddTotalCount(date)
	}
	//如果当前job已经不是jinkens的当前job，则数据库状态位置真。
	for {		
		lastCompletedBuild := JenkinsJobStatusbyName(reportnumber, projectname)
		if lastCompletedBuild == reportnumber {			
			fmt.Println("测试完成，更新测试状态")		
			plan.UpdateStatus(planid)
			//增加通过job计数
			record.AddPassCount(date)
			cost := plan.GetExectTime(planid)
			record.AddExectTime(date, cost)
			break
	} else if lastCompletedBuild > reportnumber {
		fmt.Println("测试完成，更新测试状态")		
		plan.UpdateStatus(planid)
		//增加失败job计数
		record.AddFailCount(date)
		cost := plan.GetExectTime(planid)
		record.AddExectTime(date, cost)
		break
	} else {
		continue
	}
	} 
}


func PlanGet(key string) models.PlanCase {	
	plan := models.PlanCase{}
	plan = plan.Get(key)
	return plan
}

func PlanGetList() []models.PlanCase {	
	plan := models.PlanCase{}
	plans := plan.GetList()
	return plans
}

func PlanDelete(key string) string {	
	plan := models.PlanCase{}
	plan.Delete(key)
	return "DELETE FINISH"
}


func ToPlanResult(planid string, casetotal uint16, casepass uint16, casefail uint16, caseomit uint16) string {
    plan := models.PlanCase{
		PlanTotalCase: casetotal,
		PlanPassCase: casepass,
		PlanFailCase: casefail,
		PlanOmitCase: caseomit,
	}
	//fmt.Printf("sddddddd:%v", plan)
	plan.Update(planid, plan)
	return "success"
}